package com.example.demo.controller;

import com.example.demo.entity.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    // 获取所有产品
    @GetMapping
    public List<Product> getAllProducts(@RequestParam(required = false) String categoryName) {
        if (categoryName != null) {
            return productService.getProductsByCategoryName(categoryName);
        }
        return productService.getAllProducts();
    }

    // 根据ID获取产品
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        Optional<Product> product = productService.getProductById(id);
        if (product.isPresent()) {
            return ResponseEntity.ok(product.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据ID获取产品图片URL
    @GetMapping("/{id}/images")
    public ResponseEntity<?> getProductImages(@PathVariable Long id) {
        String[] images = productService.getProductImages(id);
        if (images.length > 0) {
            return ResponseEntity.ok().body(images);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建新产品
    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        productService.saveProduct(product);
        return product;
    }

    // 更新产品
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
        Optional<Product> product = productService.getProductById(id);
        if (product.isPresent()) {
            Product updatedProduct = product.get();
            updatedProduct.setCategoryId(productDetails.getCategoryId());
            updatedProduct.setName(productDetails.getName());
            updatedProduct.setDescription(productDetails.getDescription());
            updatedProduct.setPrice(productDetails.getPrice());
            updatedProduct.setImages(productDetails.getImages());
            updatedProduct.setType(productDetails.getType());
            productService.updateProduct(updatedProduct);
            return ResponseEntity.ok(updatedProduct);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除产品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
}
